package com.tingyuge.thinking.spring.data.binding;

import com.tingyuge.thinking.spring.ioc.overview.domain.Company;
import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2021/12/12
 * @description
 * @see  DataBinder
 */
public class DataBindDemo {

    public static void main(String[] args) {
        User user = new User();
        //1. 创建dataBinder
        DataBinder dataBinder = new DataBinder(user,"user");
        Map<String, Object> source = new HashMap<>();
        source.put("id", 1);
        source.put("name", "xiaodao");
        //propertyValues 存在 user 不存在的属性值
        //dataBinder 特性二:  忽略了未知的属性
        source.put("age", 19);

        //b propertyValues 存在一个嵌套属性 比如 company.name
        // 特性一: 支持嵌套属性
        source.put("company.name", "红蝎军团");

        //调整自动增加嵌套路劲 true--->false  如果是false 就 不能嵌套需要一层一层的放对象
      //  source.put("company", new Company());
        dataBinder.setAutoGrowNestedPaths(false);
        //忽略非法字段
        dataBinder.setIgnoreInvalidFields(true);

        //白名单
        dataBinder.setRequiredFields("id","name","city");




        MutablePropertyValues propertyValues = new MutablePropertyValues(source);
        dataBinder.bind(propertyValues);
        //3.输出 user 内容
        //绑定结果(结果包含错误文案 code 不会抛出异常)
        BindingResult bindingResult = dataBinder.getBindingResult();
        System.out.println(bindingResult);
        System.out.println(user);
    }
}
